package com.wooboo.dsp.redis.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.wooboo.server.ext.Config;
import com.wooboo.server.ext.util.NumberUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

public class RedisSharedClient extends AbstractSharedRedis {

    private ShardedJedisPool shardedJedisPool;//切片连接池
    private static RedisSharedClient redisClient;
    private String redis_ip=Config.getValue("redis.ips");
	private String redis_ports=Config.getValue("redis.ports");
    private RedisSharedClient() { 
        initialShardedPool(); 
    } 
	
    public static RedisSharedClient getInstance(){
        if(redisClient==null){
            synchronized (RedisSharedClient.class) {
                if(redisClient==null) redisClient = new RedisSharedClient();
            }
        }
        
        return redisClient;
    }


    public ShardedJedis getShardedJedis() {
        return  shardedJedisPool.getResource();
    }

    /** 
     * 初始化切片池 
     */ 
    private void initialShardedPool(){ 
        // 池基本配置 
        JedisPoolConfig config = new JedisPoolConfig(); 
        config.setMaxTotal(30); 
        config.setMaxIdle(5); 
        config.setMaxWaitMillis(1000l); 
        config.setTestOnBorrow(false); 
        
        // slave链接 
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); 
        
        String[] ips = redis_ip.split(",");
        String[] ports = redis_ports.split(",");
        for(int i=0;i<ips.length;i++){
        	JedisShardInfo jedis = new JedisShardInfo(ips[i], NumberUtil.getInteger(ports[i]));
        	//jedis.setPassword("");
        	shards.add(jedis);
        }
        shardedJedisPool = new ShardedJedisPool(config, shards, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
    } 

    public void Close() {     
        shardedJedisPool.close();
    }

	public Set<String> queryAdInfo2Redis(String key){
		return keys(key);
	}

	@Override
	public ShardedJedis getJedis() {
		 return  shardedJedisPool.getResource();
	}  
    
	public static void main(String[] args){
		RedisSharedClient.getInstance().setex("note", 20, "haha");
		String str = RedisSharedClient.getInstance().get("note");
		
		Set<String> s = RedisSharedClient.getInstance().keys(".*");
		
		System.out.println(s.size()+ str);
	}
	

}
